import MKLog from "../MKLog";

/**
 * Author: ling_feng
 * Date: 2018.5.23
 * CopyRight:
 * 心跳类
 */

export default class HeartBeatHandler{
    m_idle :number = 10.0;
    m_maxMissCount :number = 2;
    m_curMissCount :number = 0;
    m_idleCallBack :Function = null;
    m_timeOutCallBack :Function = null;
    m_missCallBack :Function = null;
    m_logName :string = "";
    m_heartSchedule :number = -1;

    m_testTime:number;

    constructor(){
        
    }

    /**
     * 执行心跳
     */
    startIdle(){
        this.m_curMissCount = 0;
        if(this.m_heartSchedule != -1){
            clearInterval(this.m_heartSchedule);
        }
        if (this.m_idle > 0){
            this.m_testTime = new Date().getTime();
            this.m_heartSchedule = setInterval(this.onIdleTimer.bind(this), this.m_idle * 1000);
        }

        // MKLog.log(this.m_logName + " start idle.");
    }

    /**
     * 停止心跳
     */
    stopIdle(){
        this.m_curMissCount = 0;
        if(this.m_heartSchedule != -1){
            clearInterval(this.m_heartSchedule);
        }
        // MKLog.log(this.m_logName + " stop idle.");
    }

    /**
     * 接收心跳返回
     */
    onReceiveHeartBeat(){
        this.m_curMissCount = 0;
        // MKLog.log(this.m_logName + " receive heart beat.");
    }

    /**
     * 发送心跳
     */
    sendIdle(){
        this.m_curMissCount++;
        if (this.m_curMissCount == 2){
            MKLog.log("[HeartBeatHandler] m_logName =", this.m_logName, " miss heart beat.");
            if (this.m_missCallBack != null){
                this.m_missCallBack();
            }
        }

        if (this.m_maxMissCount > 0 && this.m_curMissCount > this.m_maxMissCount){
            this.onHeartBeatTimeOut();
        }
        else{
            //MKLog.log(this.m_logName + " send idle.");
            if (this.m_idleCallBack != null){
                this.m_idleCallBack();
            }
        }
    }

    /**
     * 定时心跳
     * @param 频率
     */
    
    onIdleTimer(){
        // let nowTime = new Date().getTime();
        // let dt = nowTime - this.m_testTime;
        // this.m_testTime = nowTime;
        let dt = -1
        //MKLog.log("onIdleTimer dt = ", dt, ", m_idle =", this.m_idle, ", m_maxMissCount =", this.m_maxMissCount);
        
        if (dt > this.m_idle * this.m_maxMissCount * 1000){
            this.onHeartBeatTimeOut();
        }
        else{
            this.sendIdle();
        }
    }

    /**
     * 心跳超时
     */
    onHeartBeatTimeOut(){
        MKLog.log("[HeartBeatHandler] at ", this.m_logName, " heart beat time out.");

        this.stopIdle();

        if (this.m_timeOutCallBack != null){
            this.m_timeOutCallBack();
        }
    }
}